package Ide;

import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;


public class NumberedEditor extends StyledEditorKit
{

    public NumberedEditor()
    {
    }

    public ViewFactory getViewFactory()
    {
        return new NumberedViewFactory();
    }

    private static final long serialVersionUID = 1L;
}

class NumberedViewFactory
implements ViewFactory
{

NumberedViewFactory()
{
}

public View create(Element elem)
{
    String kind = elem.getName();
    if(kind != null)
    {
        if(kind.equals("content"))
            return new LabelView(elem);
        if(kind.equals("paragraph"))
            return new NumberedParagraphView(elem);
        if(kind.equals("section"))
            return new BoxView(elem, 1);
        if(kind.equals("component"))
            return new ComponentView(elem);
        if(kind.equals("icon"))
            return new IconView(elem);
    }
    return new LabelView(elem);
}
}

class NumberedParagraphView extends ParagraphView
{

public NumberedParagraphView(Element e)
{
    super(e);
    short top = 0;
    short left = 0;
    short bottom = 0;
    short right = 0;
    setInsets(top, left, bottom, right);
}

protected void setInsets(short top, short left, short bottom, short right)
{
    super.setInsets(top, (short)(left + NUMBERS_WIDTH), bottom, right);
}

public void paintChild(Graphics g, Rectangle r, int n)
{
    super.paintChild(g, r, n);
    int previousLineCount = getPreviousLineCount();
    int numberX = r.x - getLeftInset();
    int numberY = (r.y + r.height) - 5;
    g.drawString(Integer.toString(previousLineCount + n + 1), numberX, numberY);
}

public int getPreviousLineCount()
{
    int lineCount = 0;
    View parent = getParent();
    int count = parent.getViewCount();
    for(int i = 0; i < count; i++)
    {
        if(parent.getView(i) == this)
            break;
        lineCount += parent.getView(i).getViewCount();
    }

    return lineCount;
}

public static short NUMBERS_WIDTH = 25;

}